package redora.rdo.client.upgrade;

import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.HTMLTable.Cell;
import com.smartgwt.client.util.JSON;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;

public class RedoraConfigurationCanvas extends VLayout {

	final String baseUpgradeUrl = GWT.getModuleBaseURL() + "modelFieldsView.do";

	String baseUrl = URL.encode(GWT.getModuleBaseURL()
			+ "redoraConfigurationOperations.do?");

	FlexTable table = new FlexTable();

	private int selectedRow = -1;

	public RedoraConfigurationCanvas() {
		this.setWidth100();
		this.setHeight100();
		this.setLayoutMargin(5);

		final Label label = new Label();

		IButton upgrade = new IButton("upgrade");
		upgrade.addClickHandler(new ClickHandler() {
			String url = URL.encode(baseUpgradeUrl + "?action=upgradeTable");
			RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);

			public void onClick(ClickEvent arg0) {
				builder.setCallback(new RequestCallback() {
					public void onError(Request request, Throwable exception) {
						SC.warn("upgrade failed!");
					}

					public void onResponseReceived(Request request,
							Response response) {
						label.setContents(response.getText());
						getScriptList();
					}
				});
				try {
					builder.send();
				} catch (RequestException e) {
					e.printStackTrace();
				}
			}

		});

		IButton check = new IButton("check");
		check.addClickHandler(new ClickHandler() {
			String url = URL.encode(baseUpgradeUrl + "?action=check");
			RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);

			public void onClick(ClickEvent arg0) {
				builder.setCallback(new RequestCallback() {
					public void onError(Request request, Throwable exception) {
						SC.warn("check failed!");
					}

					public void onResponseReceived(Request request,
							Response response) {
						label.setContents(response.getText());
					}
				});
				try {
					builder.send();
				} catch (RequestException e) {
					e.printStackTrace();
				}
			}

		});
		HLayout layout = new HLayout();
		layout.setHeight("5%");
		layout.addMember(upgrade);
		layout.addMember(check);

		getScriptList();

		addSimpleSelectionModel(table);
		table.setWidth("1000");
		table.setCellSpacing(0);
		table.setBorderWidth(1);

		this.addMember(layout);
		table.setHeight("50%");
		//this.addMember(table);

		this.addMember(label);
		this.draw();
	}

	private void addSimpleSelectionModel(final FlexTable table) {
		table
				.addClickHandler(new com.google.gwt.event.dom.client.ClickHandler() {
					public void onClick(
							com.google.gwt.event.dom.client.ClickEvent event) {
						Cell cell = table.getCellForEvent(event);
						if (cell != null) {
							if (selectedRow != -1) {
								DOM.setStyleAttribute(table.getRowFormatter()
										.getElement(selectedRow),
										"backgroundColor", "");
							}
							selectedRow = cell.getRowIndex();
							if (selectedRow != -1) {
								DOM.setStyleAttribute(table.getRowFormatter()
										.getElement(selectedRow),
										"backgroundColor", "#adcce7");
							}
						}
					}
				});
	}

	private void getScriptList() {
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL
				.encode(baseUrl + "_operationType=fetch"));
		builder.setCallback(new RequestCallback() {
			public void onError(Request request, Throwable exception) {
				SC.warn("execute failed!");
			}

			public void onResponseReceived(Request request, Response response) {
				JSONObject object = new JSONObject(JSON.decode(response
						.getText()));
				JSONArray jsonRedoraConfigurations = object.get("response")
						.isObject().get("data").isArray();
				copyValue(table, jsonRedoraConfigurations);

			}
		});
		try {
			builder.send();
		} catch (RequestException e) {
			e.printStackTrace();
		}
	}

	private void copyValue(FlexTable table, JSONArray array) {
		table.setText(0, 0, "id");
		table.setText(0, 1, "scriptName");
		table.setText(0, 2, "status");
		table.setText(0, 3, "output");
		table.setText(0, 4, "creationDate");
		table.setText(0, 5, "updateDate");
		for (int i = 0; i < array.size(); i++) {
			JSONObject value = array.get(i).isObject();
			if (value.get("id") != null
					&& !value.get("id").toString().equalsIgnoreCase("null"))
				table.setText(i + 1, 0, value.get("id").toString());
			else
				table.setText(i + 1, 0, "");
			if (value.get("scriptName") != null
					&& !value.get("scriptName").toString().equalsIgnoreCase(
							"null")) {
				final Hyperlink link = new Hyperlink();
				link.setText(value.get("scriptName").isString().stringValue());
				link
						.addClickHandler(new com.google.gwt.event.dom.client.ClickHandler() {

							public void onClick(
									com.google.gwt.event.dom.client.ClickEvent arg0) {
								RequestBuilder builder = new RequestBuilder(
										RequestBuilder.GET,
										URL
												.encode(baseUrl
														+ "_operationType=executeScript"
														+ "&scriptName="
														+ link.getText()));
								builder.setCallback(new RequestCallback() {
									public void onError(Request request,
											Throwable exception) {
										SC.warn("executeScript failed!");
									}

									public void onResponseReceived(
											Request request, Response response) {
										getScriptList();
									}
								});
								try {
									builder.send();
								} catch (RequestException e) {
									e.printStackTrace();
								}
							}

						});
				table.setWidget(i + 1, 1, link);
			} else
				table.setText(i + 1, 1, "");
			if (value.get("status") != null
					&& !value.get("status").toString().equalsIgnoreCase("null"))
				table.setText(i + 1, 2, value.get("status").isString()
						.stringValue());
			else
				table.setText(i + 1, 2, " ");
			if (value.get("output") != null
					&& !value.get("output").toString().equalsIgnoreCase("null"))
				table.setText(i + 1, 3, value.get("output").isString()
						.stringValue());
			else
				table.setText(i + 1, 3, null);
			if (value.get("creationDate") != null
					&& !value.get("creationDate").toString().equalsIgnoreCase(
							"null"))
				table.setText(i + 1, 4, value.get("creationDate").isString()
						.stringValue());
			else
				table.setText(i + 1, 4, "");
			if (value.get("updateDate") != null
					&& !value.get("updateDate").toString().equalsIgnoreCase(
							"null"))
				table.setText(i + 1, 5, value.get("updateDate").isString()
						.stringValue());
			else
				table.setText(i + 1, 5, "");
		}
	}

}
